package main

import (

	"strconv"
	"github.com/boltdb/bolt"
	"fmt"
	"github.com/xuri/excelize"
	"match-spider/util/boltdb"
	"strings"
	"regexp"
	"time"
)

/**
格式化历史数据
t1 主队
t2 客队
return
	f1	最近一年交锋胜率（最近一年无比赛则为0）
	f2	最近一年交锋平均赢球数（比分差作和／场数）
	f3	最近比赛的胜率差
	f4	最近比赛的平均赢球数差
	f5 	最近比赛的传递性胜率差
	f6	最近比赛的传递性平均赢球数（（A与C比分差-B与C比分差）／场数）
 */
func formatData3(league string,startAt string,t1 string,t2 string,text string)(float64,float64,float64,float64,float64,float64) {
	reg, _ := regexp.Compile("\\[[\\S\\s]+?]")
	//主队
	t1= reg.ReplaceAllString(t1, "")
	//客队
	t2= reg.ReplaceAllString(t2, "")
	s:=strings.Split(text,"$$$$")
	m:=strings.Split(s[1],"$$")
	//最近交锋数据处理
	bet:=strings.Split(m[0],"!")
	betWin:=float64(0)
	betScore:=float64(0)
	betTotal:=float64(0)

	for _,v:=range bet{
		slice:=strings.Split(v,"^")
		//年度差不超过1
		time1,_:=time.Parse("20060102150405",slice[0])
		time2,_:=time.Parse("06-01-02 15:04",startAt)
		if time2.Year()-time1.Year()>1{
			continue
		}
		ta:=slice[2]
		sa,_:=strconv.ParseFloat(slice[4],64)
		sb,_:=strconv.ParseFloat(slice[5],64)
		if strings.Compare(t1,ta)==0{
			betScore+=sa-sb
			if sa>sb{
				betWin++
			}
		}else{
			betScore+=sb-sa
			if sa<sb{
				betWin++
			}
		}
		betTotal++
	}
	//交锋胜率差
	f1:=float64(0)
	//平均赢球数
	f2:=float64(0)
	if betTotal>0{
		f1=betWin/betTotal
		f2=betScore/betTotal
	}

	//处理最近比赛数据
	mmMatchTotal1:=float64(0)//总比赛场数
	mmMatchTotal2:=float64(0)
	mmScoreTotal1:=float64(0)//总得分
	mmScoreTotal2:=float64(0)
	mmWinTotal1:=float64(0)//胜利场数
	mmWinTotal2:=float64(0)
	//传递性数据
	ttMatchTotal:=float64(0)//总比赛场数
	ttScoreTotal:=float64(0)//总得分
	ttWinTotal1:=float64(0)//胜利场数
	ttWinTotal2:=float64(0)

	mmMapIndex:=make(map[string]interface{})
	for k,v:=range m{
		if k==0{
			//第一条是交锋数据，放弃
			continue
		}
		mm:=strings.Split(v,"!")
		for _,v1:=range mm {

			if strings.Contains(v1,t1)&&strings.Contains(v1,t2){
				//去掉重复的交锋数据
				continue
			}
			ss:=strings.Split(v1,"!")

			if strings.Contains(v1,t1){
				//主队数据
				mmMatchTotal1++
				for _,vss:=range ss {

					d:=strings.Split(vss,"^")
					if len(d)<12{
						continue
					}
					ta:=d[2]
					tb:=d[3]
					sa,_:=strconv.ParseFloat(d[4],64)
					sb,_:=strconv.ParseFloat(d[5],64)
					//对阵球队
					opponent:=tb
					ff1:=sa-sb
					if strings.Compare(t1,ta)!=0{
						ff1=sb-sa
						opponent=ta
					}
					mmScoreTotal1+=ff1
					if ff1>0{
						mmWinTotal1++
					}
					//传递性处理
					if mmMapIndex[opponent]==nil{
						mmMapIndex[opponent]=ff1
					}else{
						//传递性比赛
						score:=mmMapIndex[opponent].(float64)
						if ff1>0{
							ttWinTotal1++
						}
						ttScoreTotal+=ff1-score
						ttMatchTotal++
					}
				}
			}
			if strings.Contains(v1,t2){
				//客队数据
				mmMatchTotal2++
				for _,vss:=range ss {
					d:=strings.Split(vss,"^")
					if len(d)<12{
						continue
					}
					ta:=d[2]
					tb:=d[3]
					sa,_:=strconv.ParseFloat(d[4],64)
					sb,_:=strconv.ParseFloat(d[5],64)

					//对阵球队
					opponent:=tb
					ff1:=sa-sb
					if strings.Compare(t2,ta)!=0{
						ff1=sb-sa
						opponent=ta
					}
					mmScoreTotal2+=ff1
					if ff1>0{
						mmWinTotal2++
					}
					//传递性处理
					if mmMapIndex[opponent]==nil{
						mmMapIndex[opponent]=ff1
					}else{
						//传递性比赛
						score:=mmMapIndex[opponent].(float64)
						if ff1>0{
							ttWinTotal2++
						}
						ttScoreTotal+=score-ff1
						ttMatchTotal++
					}
				}
			}
		}
	}
	f3:=float64(0)
	f4:=float64(0)
	f5:=float64(0)
	f6:=float64(0)
	if mmMatchTotal1>0&&mmMatchTotal2>0{
		f3=mmWinTotal1/mmMatchTotal1-mmWinTotal2/mmMatchTotal2
		f4=mmScoreTotal1/mmMatchTotal1-mmScoreTotal2/mmMatchTotal2
	}
	if ttMatchTotal>0{
		f5=(ttWinTotal1-ttWinTotal2)/ttMatchTotal
		f6=ttScoreTotal/ttMatchTotal
	}

	return f1,f2,f3,f4,f5,f6
}
/**
澳门盘口为0.25
 */
func checkAsia2(data string) (bool,float64) {
	if !strings.Contains(data,"澳门"){
		return false,float64(0)
	}
	asiaSlice:=strings.Split(data,"!")
	asiaScore:=""

	for _,v:=range asiaSlice{
		d:=strings.Split(v,"^")

		if d[0]=="澳门"&&strings.Contains(d[6],"0.25"){
			asiaScore=d[6]
		}
	}
	if asiaScore==""{
		return false,float64(0)
	}

	f,_:=strconv.ParseFloat(asiaScore,64)
	return true,f
}
func checkOverunder2(data string) (bool,float64) {
	overunderSlice:=strings.Split(data,"!")

	total:=float64(0)
	for _,v:=range overunderSlice{
		d:=strings.Split(v,"^")

		val,_:=strconv.ParseFloat(d[6],64)
		total+=val
	}
	avg:=total/float64(len(overunderSlice))

	if avg>=2&&avg<3{
		return true,avg
	}
	return false,float64(0)
}
func score3(fn func([]interface{},int)){
	i:=0
	boltdb.ScanTx("matchs-2016", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {
			b.ForEach(func(k, v []byte) error {
				content:=string(v)
				s:=strings.Split(content,"^")
				win:=0

				league:=s[1]
				startAt:=s[2]
				t1:=s[3]
				t2:=s[5]
				s1,_:=strconv.ParseFloat(s[4],64)
				s2,_:=strconv.ParseFloat(s[6],64)

				boltdb.Get("asia-2016",league,string(k), func(asia string) {
					b1,f1:=checkAsia2(asia)
					if !b1{
						return
					}

					boltdb.Get("overunder-2016",league,string(k), func(data string) {
						//大小球盘口在2-2.75之间

						b2,_:=checkOverunder2(data)
						if !b2{
							return
						}

						boltdb.Get("lastmatch-2016",league,string(k), func(text string) {
							//判断输赢
							//去掉没有联赛的比赛
							if !strings.Contains(text,"总"){
								return
							}
							ff1,ff2,ff3,ff4,ff5,ff6:=formatData3(league,startAt,t1,t2,text)

							if s1-f1-s2>0{
								win=1
							}
							i++
							slice:=[]interface{}{string(k),ff1,ff2,ff3,ff4,ff5,ff6,f1,win}
							fn(slice,i)
						})


					})
				})

				return nil
			})
			return nil
		})

	})
	fmt.Println(i)
}

func main()  {
	e:=[]string{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
	xlsx := excelize.NewFile()

	categories := []string{
		"id",
		"交锋胜率",
		"交锋赢球",
		"历史胜率",
		"历史赢球",
		"传递胜率",
		"传递赢球",
		"盘口",
		"输赢",
	}
	for k,v:=range categories{
		len:=int(k/26)
		s:=""
		if len>0{
			s+=e[len-1]+e[k%26]
		}else{
			s+=e[k%26]
		}

		xlsx.SetCellValue("Sheet1",s+"1", v)
	}
	score3(func(s []interface{}, i int) {
		for k,v:=range s{
			len:=int(k/26)
			s:=""
			if len>0{
				s+=e[len-1]+e[k%26]
			}else{
				s+=e[k%26]
			}
			xlsx.SetCellValue("Sheet1",s+strconv.Itoa(i+1), v)
		}
	})
	err := xlsx.SaveAs("./Workbook.xlsx")
	if err != nil {
		fmt.Println(err)
	}

}
